import { registerMicroApps, start } from 'qiankun'

import { filterApps, microConfig } from './registerApp'

import { addGlobalUncaughtErrorHandler } from 'qiankun'

import Vue from 'vue'
import { loadMicroApp } from 'qiankun'

// 微应用注册
export const registerApps = () => {
  const _apps = filterApps()
  console.log('sub_apps', _apps)
  registerMicroApps(_apps, microConfig)
  start({
    prefetch: 'all', // 可选，是否开启预加载，默认为 true。
    sandbox: {
       experimentalStyleIsolation: true,
       speedy: true
      }, // 可选，是否开启沙箱，默认为 true。// 从而确保微应用的样式不会对全局造成影响。
    singular: false // 可选，是否为单实例场景，单实例指的是同一时间只会渲染一个微应用。默认为 true。
  })
}

// 微应用注册
export const importComponents = async() => {
  const _apps = filterApps()
  if (!window.commonComponents) {
    window.commonComponents = []
  } else {
    // 如果子应用mount过直接调用，不要再load
    if (window.commonComponents.flag) {
      return
    }
  }
  const commonComponent = window.commonComponents
  const apps = []
  _apps.forEach((item) => {
    if (item.entry && item.activeRule) {
      item.container = '#hideContainer'
      item.props.commonComponents = commonComponent
      apps.push(item)
    }
  })
  console.log('导入子应用组件')
  console.log(apps)
  var subApps = []
  for await (const item of apps) {
    subApps = loadMicroApp(item, {
      sandbox: {
        // experimentalStyleIsolation: true,
        speedy: true
      }
    })
    await subApps.mountPromise
  }
  // await subApps.unmount()
  console.log('获取到所有子应用组件')
  if (commonComponent.component) {
    // 循环全部注册为组件
    commonComponent.component.forEach(component => {
      Vue.component(component.name, component)
    })
    window.commonComponents.flag = true
  }
}

// 根据应用名注册子应用组件
export const importComponent = async(subApp, componentName) => {
  console.log('开始导入子应用组件', subApp, componentName)
  if (!subApp || !subApp.entry || !subApp.activeRule || !componentName) {
    return
  }
  if (!window.commonComponents) {
    window.commonComponents = []
  } else {
    // 如果子应用mount过直接调用，不要再load
    if (window.commonComponents[componentName]) {
      return
    }
  }
  const commonComponent = window.commonComponents
  const store = require('./globalState')
  const props = {
    'commonComponents': commonComponent,
    'getGlobalState': store,
    'bus': Vue.prototype.$bus
  }
  subApp.container = '#hideContainer'
  subApp.props = props
  var subApps = loadMicroApp(subApp, {
    sandbox: {
      // experimentalStyleIsolation: true,
      speedy: true
    }
  })
  await subApps.mountPromise
  // await subApps.unmount()
  console.log('获取到所有子应用组件')
  if (commonComponent.component) {
    // 循环全部注册为组件
    commonComponent.component.forEach(component => {
      Vue.component(component.name, component)
      window.commonComponents[component.name] = true
    })
  }
}

addGlobalUncaughtErrorHandler((event) => console.log(event))
